package com.xyz.graph.handler;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xyz.graph.pojo.gdata.AddVertexParamPojo;
import com.xyz.graph.pojo.gdata.edgeParam.AddEdgeParamPojo;
import com.xyz.graph.service.GDataService;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.concurrent.Callable;
import java.util.stream.Collectors;

/**
 * 数据入图
 * author：mxy
 */
@Slf4j
public class Data2GraphServiceCallable implements Callable<String> {
    private final static ObjectMapper MAPPER = new ObjectMapper();

    private GDataService gDataService;
    //AddVertexParamPojo
    private final List<AddVertexParamPojo> datalist = new ArrayList<>();

    static {
        MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }
    @Override
    public String call() throws Exception {

        String [] str = Thread.currentThread().getName().split("-");
        Thread.currentThread().setName(str[0]+"-"+str[1]+"-实体入图-"+str[3]);

        //去重
        List<AddVertexParamPojo> newVertexParamPojoList = new ArrayList<>(datalist.stream().collect(Collectors.toCollection(()->
                new TreeSet<>(Comparator.comparing(o -> o.getEntityId())))));
        //入图
        log.info("vertex 入图开始,数量：{}",newVertexParamPojoList.size());
        long start = System.currentTimeMillis();
        newVertexParamPojoList.stream().forEach(addVertexParamPojo -> {
            log.info("实体{}：{}",addVertexParamPojo.getEntityIdKey(),addVertexParamPojo.getEntityId());
            gDataService.addVertex(PreStartDoThing.getG(),addVertexParamPojo);
        });
        long end = System.currentTimeMillis();

        datalist.clear();
        log.info("添加完成，实体用时：{}s",(end-start)/1000);
        return "success";
    }

    public Data2GraphServiceCallable(List<AddVertexParamPojo> datalist,GDataService gDataService){
        //避免指令重排
        this.datalist.addAll(datalist);
        this.gDataService = gDataService;

    }
}
